package com.mojo.concurrent.lock;

import com.sun.org.apache.bcel.internal.generic.LoadClass;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition接口示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/18 11:42
 */
public class ConditionDemo01 {
    static Lock lock = new ReentrantLock();
    static Condition c = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        // Condition c = new ReentrantLock().newCondition();
        // c.await();
        // c.await(1, TimeUnit.SECONDS);
        // c.signal();
        // c.signalAll();
        // c.awaitUninterruptibly();
        new Thread("线程1") {
            @Override
            public void run() {
                await();
            }
        }.start();
        new Thread("线程2") {
            @Override
            public void run() {
                signal();
            }
        }.start();
        new Thread("线程3") {
            @Override
            public void run() {
                signal();
            }
        }.start();

    }

    public static void await() {
        lock.lock();
        try {
            c.await();
            System.out.println("消费。。。");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public static void signal() {
        lock.lock();
        try {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            c.signal();
            System.out.println(Thread.currentThread().getName() + "生产。。。");
        } finally {
            lock.unlock();
        }
    }
}
